package com.car.carmgr.controller;

import com.car.carmgr.bean.*;
import com.car.carmgr.service.*;
import com.car.carmgr.util.AjaxResult;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("sys")
public class SystemRestController {

    @Autowired
    private MenuService menuService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserService userService;

    @Autowired
    private LogInfoService logInfoService;

    @Autowired
    private NewsService newsService;

    @RequestMapping("indexLeftMenu")
    public Object indexLeftMenu(Integer id,HttpSession session){

        //获取登陆对象
        Object session_user = session.getAttribute("session_user");
        if(session_user == null){
            return null;
        }
        User user = (User) session_user;
        List<Menu> all = menuService.findById(id);
        Map<String, Object> map = new HashMap<>();
        //超级管理员
        if(user.getType() == 1){
            if(id == null){
                id =1;
            }
            List<Menu> list = menuService.findById(id);
            map.put("contentManagement",list);
        }else{
            //普通人员：需要查询对应的菜单
            List<Menu> menus = menuService.findByUserId(user.getUserId());  //没有层级关系
            //把menu转换成有层级关系的数据
            List<Menu> list = new ArrayList<>();
            for(Menu menu:menus){
                if(menu.getPid()!=null && menu.getPid() == 1){
                    list.add(menu);
                    continue;
                }
                for(Menu menu1:list){
                    if(menu.getPid() == menu1.getId()){
                        menu1.getChildren().add(menu);
                    }
                }
            }
            map.put("contentManagement",list);
        }
        return map;
    }

    @RequestMapping("menu/menuLeftJson")
    public AjaxResult menuLeftJson(){
        List<Menu> all = menuService.findById(0);
        return AjaxResult.ok(all);
    }

    @RequestMapping("menu/menuRightJson")
    public AjaxResult menuRightJson(String name,Integer page,Integer limit,Integer id){
        PageInfo pageInfo = menuService.findByWhere(name, page, limit,id);
        Integer count = menuService.getCountByWhere(name,id);
        return AjaxResult.ok(count,pageInfo.getList());
    }

    @RequestMapping("menu/menuAddOrUpdate")
    public AjaxResult menuRightJson(Menu menu){

        if(menu.getId() == null){
            int i = menuService.addMenu(menu);
            if(i>0){
                return AjaxResult.ADD_SUCCESS();
            }else{
                return AjaxResult.ADD_FAILED();
            }
        }else{
            int i = menuService.updateMenu(menu);
            if(i>0){
                return AjaxResult.UPD_SUCCESS();
            }else{
                return AjaxResult.UPD_FAILED();
            }
        }

    }

    @RequestMapping("menu/menuDelete")
    public AjaxResult menuDelete(Integer id){

        int count = menuService.findByPid(id);

        if(count!=0){
            return AjaxResult.DEL_HAS_CH();
        }else{
            int i = menuService.delMenu(id);
            if(i>0){
                return AjaxResult.DEL_SUCCESS();
            }else{
                return AjaxResult.DEL_FAILED();
            }
        }
    }

    @RequestMapping("role/roleRightJson")
    public AjaxResult roleRightJson(String roleName,String roleDesc,Integer page,Integer limit){
        PageInfo<Role> pageInfo = roleService.findRoleByWhere(roleName,roleDesc, page, limit);
        Integer count = roleService.getCountByWhere(roleName,roleDesc);
        return AjaxResult.ok(count,pageInfo.getList());
    }

    @RequestMapping("role/roleAddOrUpdate")
    public AjaxResult roleAddOrUpdate(Role role){

        if(role.getRoleId() == null){
            int i = roleService.insert(role);
            if(i>0){
                return AjaxResult.ADD_SUCCESS();
            }else{
                return AjaxResult.ADD_FAILED();
            }
        }else{
            int i = roleService.updateRole(role);
            if(i>0){
                return AjaxResult.UPD_SUCCESS();
            }else{
                return AjaxResult.UPD_FAILED();
            }
        }
    }

    @RequestMapping("role/roleLeftJson")
    public AjaxResult roleLeftJson(Integer roleId){
        //所有的菜单
        List<Menu> all = menuService.findAll();

        //当前角色拥有的菜单
        List<Menu> menuByRoleId = menuService.findMenuByRoleId(roleId);

        /*方法一*/
        /*for(Menu m: all){
            //获取当前菜单m
            Integer id = m.getId();
            //判断该角色是否有改菜单
            Boolean flag = false;
            for (Menu m2: menuByRoleId){
                if(id == m2.getId()){
                    flag = true;
                    break;
                }
            }

            if(flag){
                m.setCheckArr("1");
            }
        }*/
        for(Menu m: all){
            for (Menu m2: menuByRoleId){
                if(m.getId() == m2.getId()){
                    m.setCheckArr("1");
                    break;
                }
            }
        }

        return AjaxResult.ok(all);
    }

    @RequestMapping("role/allotMenuByRoleId")
    public String allotMenuByRoleId(Integer roleId,String roleIds){
        String[] split = roleIds.split(",");
        Integer[] arr = new Integer[split.length];
        for(int i = 0;i<arr.length;i++){
            arr[i] = Integer.valueOf(split[i]);
        }
        int i = roleService.updRoleMenuByRoleId(roleId,arr);
        if(i>0){
            return "1";
        }else{
            return "";
        }
    }

    @RequestMapping("role/roleDelete")
    public AjaxResult roleDelete(Integer id){
        int i = roleService.deleteRoleById(id);
        if(i>0){
            return AjaxResult.DEL_SUCCESS();
        }else{
            return AjaxResult.DEL_FAILED();
        }
    }

    @RequestMapping("user/userRightJson")
    public AjaxResult userRightJson(String loginName,String realName,String identity,String address,String phone,Integer sex, Integer page,Integer limit){
        PageInfo<User> pageInfo = userService.findUserByWhere(loginName,realName,identity,address,phone,sex,page, limit);
        Integer count = userService.getCountByWhere(loginName,realName,identity,address,phone,sex);
        return AjaxResult.ok(count,pageInfo.getList());
    }

    @RequestMapping("user/userAddOrUpdate")
    public AjaxResult userAddOrUpdate(User user){

        if(user.getUserId() == null){
            int i = userService.insertUser(user);
            if(i>0){
                return AjaxResult.ADD_SUCCESS();
            }else{
                return AjaxResult.ADD_FAILED();
            }
        }else{
            int i = userService.updateUser(user);
            if(i>0){
                return AjaxResult.UPD_SUCCESS();
            }else{
                return AjaxResult.UPD_FAILED();
            }
        }
    }

    @RequestMapping("user/userDelete")
    public AjaxResult userDelete(Integer id){
        int i = userService.deleteUserById(id);
        if(i>0){
            return AjaxResult.DEL_SUCCESS();
        }else{
            return AjaxResult.DEL_FAILED();
        }
    }

    @RequestMapping("user/resetUserPwd")
    public AjaxResult resetUserPwd(Integer id){
        int i = userService.resetUserPwd(id);
        if(i>0){
            return AjaxResult.RESETPWD_SUCCESS();
        }else{
            return AjaxResult.RESETPWD_FAILED();
        }
    }

    @RequestMapping("user/deleteSomeUser")
    public AjaxResult deleteSomeUser(String userIds){
        int i = userService.deleteSomeUser(userIds.split(","));
        if(i>0){
            return AjaxResult.DELSOME_SUCCESS();
        }else{
            return AjaxResult.DELSOME_FAILED();
        }
    }

    @RequestMapping("user/initUserRole")
    public AjaxResult initUserRole(String roleName,String roleDesc,Integer page,Integer limit,String userId){
        PageInfo<Role> pageInfo = roleService.findRoleByWhere(roleName,roleDesc, page, limit);
        Integer count = roleService.getCountByWhere(roleName,roleDesc);
        return AjaxResult.ok(count,pageInfo.getList());
    }

    @RequestMapping("user/roleAllJson")
    public AjaxResult roleAllJson(Integer userId){
        //获取所有角色
        List<Role> all = roleService.findAll();

        //获取当前用户的角色
        List<Role> RoleByUserId = roleService.findRoleByUserId(userId);

        List<Map<String, Object>> list = new ArrayList<>();
        for(Role r:all){
            Map<String, Object> map = new HashMap<>();
            // 把当前r 在 roleByUserId集合中去查找，如果存在就把属性LAY_CHECKED设为true
            Boolean flag = false;
            for (Role r2 : RoleByUserId){
                if(r.getRoleId() == r2.getRoleId()){
                    flag = true;
                    break;
                }
            }
            map.put("roleId",r.getRoleId());
            map.put("roleName",r.getRoleName());
            map.put("roleDesc",r.getRoleDesc());
            map.put("available",r.getAvailable());
            map.put("LAY_CHECKED",flag);

            list.add(map);
        }

        return AjaxResult.ok(list);
    }

    @RequestMapping("user/updRoleByUserId")
    public String updRoleByUserId(Integer userId,String roleIds){
        String[] split = roleIds.split(",");
        Integer[] arr = new Integer[split.length];
        for(int i = 0;i<arr.length;i++){
            arr[i] = Integer.valueOf(split[i]);
        }
        int i = userService.updateRoleUser(userId, arr);
        if(i>0){
            return "1";
        }else{
            return "";
        }
    }

    @RequestMapping("logInfo/logInfoRightJson")
    public AjaxResult logInfoRightJson(LogInfo logInfo, Integer page,Integer limit){
        PageInfo<LogInfo> pageInfo = logInfoService.findLogInfoByWhere(logInfo,page, limit);
        Integer count = logInfoService.getCountByWhere(logInfo);
        return AjaxResult.ok(count,pageInfo.getList());
    }

    @RequestMapping("logInfo/logInfoDelete")
    public AjaxResult logInfoDelete(Integer id){
        int i = logInfoService.deleteLogInfoById(id);
        if(i>0){
            return AjaxResult.DEL_SUCCESS();
        }else{
            return AjaxResult.DEL_FAILED();
        }
    }

    @RequestMapping("logInfo/deleteSomeLogInfo")
    public AjaxResult deleteSomeLogInfo(String logInfoIds){
        int i = logInfoService.deleteSomeLogInfo(logInfoIds.split(","));
        if(i>0){
            return AjaxResult.DELSOME_SUCCESS();
        }else{
            return AjaxResult.DELSOME_FAILED();
        }
    }

    @RequestMapping("news/newsRightJson")
    public AjaxResult newsRightJson(String title, String content,String publisherName, Integer page, Integer limit){
        PageInfo<News> pageInfo = newsService.findNewsByWhere(title,content,publisherName,page, limit);
        Integer count = newsService.getCountByWhere(title,content,publisherName);
        return AjaxResult.ok(count,pageInfo.getList());
    }

    @RequestMapping("news/newsAddOrUpdate")
    public AjaxResult newsAddOrUpdate(News news, HttpSession session){

        if(news.getId() == null){
            news.setCreateTime(new Date());
            User session_user =(User) session.getAttribute("session_user");
            news.setPublisherName(session_user.getRealName());
            int i = newsService.insertNews(news);
            if(i>0){
                return AjaxResult.ADD_SUCCESS();
            }else{
                return AjaxResult.ADD_FAILED();
            }
        }else{
            int i = newsService.updateNews(news);
            if(i>0){
                return AjaxResult.UPD_SUCCESS();
            }else{
                return AjaxResult.UPD_FAILED();
            }
        }
    }

    @RequestMapping("news/newsDelete")
    public AjaxResult newsDelete(Integer id){
        int i = newsService.deleteNewsById(id);
        if(i>0){
            return AjaxResult.DEL_SUCCESS();
        }else{
            return AjaxResult.DEL_FAILED();
        }
    }

    @RequestMapping("news/deleteSomeNews")
    public AjaxResult deleteSomeNews(String ids){
        int i = newsService.deleteSomeNews(ids.split(","));
        if(i>0){
            return AjaxResult.DELSOME_SUCCESS();
        }else{
            return AjaxResult.DELSOME_FAILED();
        }
    }

    @RequestMapping("news/findNewsById")
    public News findNewsById(Integer id){
        return newsService.findNewsById(id);
    }

}
